package com.gnerv.battle.boot.module.base.processor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Properties;

/**
 * @author Gnerv LiGen
 * 动态为mybatis添加mapper-locations配置 可以不在配置文件中添加了 如果配置文件中有 则使用配置文件中的
 */
@Slf4j
@Service
public class MybatisEnvironmentPostProcessor implements EnvironmentPostProcessor {

    private static final String BATTLE_MYBATIS_PROPERTIES = "battleMybatisProperties";
    private static final String MYBATIS_MAPPER_LOCATIONS = "mybatis.mapper-locations";
    private static final String MYBATIS_MAPPER_LOCATIONS_VALUE = "classpath*:/mapper/**/*.xml";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        boolean flag = false;
        Properties props = new Properties();
        MutablePropertySources propertySources = environment.getPropertySources();
        for (PropertySource<?> propertySource : propertySources) {
            if (propertySource instanceof EnumerablePropertySource<?> enumerablePropertySource) {
                String[] propertyNames = enumerablePropertySource.getPropertyNames();
                if (!flag) {
                    boolean contains = CollectionUtils.arrayToList(propertyNames).contains(MYBATIS_MAPPER_LOCATIONS);
                    if (contains) {
                        String propertyVal = environment.getProperty(MYBATIS_MAPPER_LOCATIONS);
                        if (propertyVal == null) {
                            props.put(MYBATIS_MAPPER_LOCATIONS, MYBATIS_MAPPER_LOCATIONS_VALUE);
                            flag = true;
                        }
                    }
                }
            }
        }
        if (!flag) {
            props.put(MYBATIS_MAPPER_LOCATIONS, MYBATIS_MAPPER_LOCATIONS_VALUE);
        }
        if (!props.isEmpty()) {
            PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource(BATTLE_MYBATIS_PROPERTIES, props);
            environment.getPropertySources().addFirst(propertiesPropertySource);
        }
        log.info("Mybatis environment post process finished");
    }
}
